package tech.aistar.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import tech.aistar.entity.*;
import tech.aistar.service.*;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private IRegisterService registerService;
    @Autowired
    private ITenantService tenantService;
    @Autowired
    private IAgentService agentService;
    @Autowired
    private ILandlordService landlordService;

    //登录初始页面
    @RequestMapping("/check")
    public String Login(String account, String password) {
        return "/login/login";
    }


    //登录成功跳主页并传身份值
    @RequestMapping("/success")
    public String Home(HttpServletRequest request) {
        String account = request.getParameter("account");
        Register register = registerService.selectByAccount(account);

        //把register放入session域中
        request.getSession().setAttribute("register", register);
        String identity = register.getIdentity();
        if (identity.equals("1")) {
            Tenant tenant = tenantService.selectByregisterId(register.getId());
            request.getSession().setAttribute("tenant", tenant);
        }
        if (identity.equals("2")) {
            Agent agent = agentService.selectByregisterId(register.getId());
            request.getSession().setAttribute("agent", agent);
        }
        if (identity.equals("3")) {
            Landlord landlord = landlordService.selectByregisterId(register.getId());
            request.getSession().setAttribute("landlord", landlord);
        }
        //转发到首页
        return "forward:/home/page";
    }


    //检测用户名是否存在
    @PostMapping("/selectaccount")
    public @ResponseBody
    Result select(String account, HttpServletRequest request) {
        Register register = registerService.selectByAccount(account);
        if (register != null) {
            request.setAttribute("register", register);
            return new Result("200", "修改成功");
        } else {
            return new Result("500", "修改失败");
        }
    }


    //检测密码是否正确
    @PostMapping("/selectpassword")
    public @ResponseBody
    Result select(String account, String password) {
        Register register = registerService.selectPassword(account);

        if (password.equals(register.getPassword())) {
            return new Result("200", "密码正确");
        } else {
            return new Result("500", "密码错误");
        }
    }

}